package modes

import (
	"fmt"
	"time"
)

/*问题表*/
type Problem struct {
	Id        int64  `json:"blem_id" xorm:"id"`                 //问题ID
	UId       int64  `json:"blem_uid" xorm:"uid"`               //学员ID
	RId       int64  `json:"blem_rid" xorm:"rid"`               // 课程分类id
	Title     string `json:"blem_title" xorm:"title"`           // 问题标题
	TitleStye string `json:"blem_title_stye" xorm:"title_stye"` // 问题类型
	Descs     string `json:"blem_descs" xorm:"descs"`           // 问题描述
	File      string `json:"blem_file" xorm:"file"`             // 图片
	At        int64  `json:"blem_at" xorm:"at"`                 //创建时间
}

func (this *Problem) TableName() string {
	return "problem"
}
func (this *Problem) Save() (int64, error) {
	this.At = time.Now().Unix()
	return Db(0).Insert(this)
}

func (this *Problem) Get() (bool, error) {
	return Db(0).Get(this)
}
func (this *Problem) delete(where string) (int64, error) {
	return Db(0).Where(where).Delete(this)
}
func (this *Problem) Del() (int64, error) {
	where := fmt.Sprintf("id =%d", this.Id)
	return this.delete(where)
}
func (this *Problem) Count(where string) (int64, error) {
	var val Problem
	return Db(0).Where(where).Count(&val)
}
func (this *Problem) update(where string, field string) (int64, error) {
	return Db(0).Where(where).Cols(field).Update(this)
}

func (this *Problem) IdSet(field string) (int64, error) {
	where := fmt.Sprintf("id = %d", this.Id)
	return this.update(where, field)
}

func (this *Problem) where(fage, count, page int, where, field string) ([]Problem, error) {
	list := make([]Problem, 0)
	var err error
	if field == "" {
		field = "id"
	}
	if 0 == fage { // 从小到大排序
		err = Db(0).Where(where).
			Asc(field).
			Limit(count, page*count).
			Find(&list)
	} else { // 从大到小排序
		err = Db(0).Where(where).
			Desc(field).
			Limit(count, page*count).
			Find(&list)
	}
	return list, err
}
func (this *Problem) List(val *Pager) error {
	val.TName = this.TableName()
	w := fmt.Sprintf("uid = %d ", this.UId)
	val.Total, _ = this.Count(w)
	list, err := this.where(val.Rules, val.Count, val.Page-1, w, "")
	if err == nil {
		val.List = list
	}
	return err
}
